package com.example.musicaiap

import android.Manifest
import android.app.Activity // Needed for SideEffect context cast
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log // Keep Log import
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge // Import enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column // Keep import if needed elsewhere, but not for wrapping AppNav
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.SideEffect // Import SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color // Need Color for Transparent default
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.LocalView // Import LocalView
import androidx.core.view.WindowCompat // Import WindowCompat
import androidx.hilt.navigation.compose.hiltViewModel // Import hiltViewModel
import androidx.media3.common.util.UnstableApi
import com.example.musicaiap.navigation.AppNavigation
import com.example.musicaiap.navigation.NavigationState
import com.example.musicaiap.service.MusicService
import com.example.musicaiap.ui.main.MainViewModel // Import MainViewModel
import com.example.musicaiap.ui.theme.MusicAIAPTheme // Corrected import
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 应用主Activity
 * 负责初始化应用，配置权限请求，以及设置导航
 */
@AndroidEntryPoint
@UnstableApi
class MainActivity : ComponentActivity() {

    /**
     * 日志标签
     */
    private val TAG = "MainActivity"

    /**
     * 权限请求回调
     * 当权限请求结果返回时会回调给它
     */
    private val _permissionResultCallback = MutableStateFlow<((Boolean) -> Unit)?>(null)
    val permissionResultCallback: StateFlow<((Boolean) -> Unit)?> = _permissionResultCallback.asStateFlow()

    /**
     * 存储权限请求启动器
     */
    private lateinit var storagePermissionLauncher: ActivityResultLauncher<String>

    /**
     * Activity创建时调用
     * 设置内容视图并初始化必要的组件
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Enable Edge-to-Edge using the helper function
        enableEdgeToEdge()

        // 初始化存储权限请求启动器
        storagePermissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            Log.d(TAG, "存储权限请求结果: $isGranted")
            _permissionResultCallback.value?.invoke(isGranted)
            _permissionResultCallback.value = null
        }

        setContent {
            MusicAIAPTheme { // Corrected theme usage
                // Get ViewModel instance
                val mainViewModel: MainViewModel = hiltViewModel()
                // Collect the global background color state
                val globalBackgroundColor by mainViewModel.globalBackgroundColor.collectAsState()
                Log.d("MainActivity", "Collected globalBackgroundColor: $globalBackgroundColor") // Add log

                // Determine if the global background is effectively transparent or the theme default
                val isUsingGlobalColor = globalBackgroundColor != Color.Transparent
                val surfaceColor = if (isUsingGlobalColor) {
                    globalBackgroundColor
                } else {
                    MaterialTheme.colorScheme.background // Use theme default if global is transparent
                }

                // Temporarily commented out for debugging global background color application
                // val view = LocalView.current
                // if (!view.isInEditMode) {
                //     SideEffect {
                //         val window = (view.context as Activity).window
                //         // Determine if the status/nav bar icons should be light or dark
                //         val useLightIcons = surfaceColor.luminance() > 0.5f
                //         WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = useLightIcons
                //         WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = useLightIcons
                //     }
                // }

                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = surfaceColor // Apply the effective background color
                 ) {
                     Box(modifier = Modifier.fillMaxSize()) { // Wrap content in a Box for alignment

                         // Temporarily commented out for debugging global background color application
                         // Box for top (status bar area) background color
                         // Only draw if a global color is set (not transparent)
                         // if (isUsingGlobalColor) {
                         //     Box(
                         //         modifier = Modifier
                         //             .fillMaxWidth()
                         //             .windowInsetsTopHeight(WindowInsets.statusBars)
                         //             .background(globalBackgroundColor)
                         //             .align(Alignment.TopCenter)
                         //     )
                         // }

                         // Temporarily commented out for debugging global background color application
                         // Box for bottom (navigation bar area) background color
                         // Only draw if a global color is set (not transparent)
                         // if (isUsingGlobalColor) {
                         //     Box(
                         //         modifier = Modifier
                         //             .fillMaxWidth()
                         //             .windowInsetsBottomHeight(WindowInsets.navigationBars)
                         //             .background(globalBackgroundColor)
                         //             .align(Alignment.BottomCenter)
                         //     )
                         // }

                         // Main App Navigation - Place it directly inside the Box
                         // It should draw *over* the background boxes
                         // Get ViewModel instance here to pass down
                         val mainViewModelInstance = mainViewModel // Use the instance obtained above

                         // 创建共享的导航状态
                         val navigationState = remember { NavigationState() }

                         // 监听权限请求回调 (Currently unused, but kept for potential future use)
                         val permissionCallback by permissionResultCallback.collectAsState()

                         // 启动应用导航
                         AppNavigation(
                             onPermissionRequest = { callback ->
                                 // 保存回调并请求权限
                                 Log.d(TAG, "收到权限请求，保存回调")
                                 _permissionResultCallback.value = callback
                                 requestStoragePermission()
                             },
                             navigationState = navigationState,
                             mainViewModel = mainViewModelInstance // Pass the instance down
                         )
                     } // End of wrapping Box
                }
            }
        }
    }

    /**
     * Activity启动时调用
     * 连接到媒体浏览器服务
     */
    @UnstableApi
    override fun onStart() {
        super.onStart()
        // 启动音乐服务
        Intent(this, MusicService::class.java).also { intent ->
            startService(intent)
        }
    }

    /**
     * 请求存储权限
     * 根据Android版本选择合适的存储权限
     * 如果已经有权限直接返回成功，否则发起权限请求
     */
    private fun requestStoragePermission() {
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+使用READ_MEDIA_AUDIO权限
            Manifest.permission.READ_MEDIA_AUDIO
        } else {
            // 旧版Android使用READ_EXTERNAL_STORAGE权限
            Manifest.permission.READ_EXTERNAL_STORAGE
        }

        Log.d(TAG, "请求权限: $permission")
        storagePermissionLauncher.launch(permission)
    }
}
